package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author Yancy
 * @program springioctest
 * @create 2021-01-21
 */
public class JdbcTest {
  public static void main(String[] args) {
    Connection connection = null;
    Statement statement = null;
    int n = 0;

    try {
      // 1.加载数据库驱动
      Class.forName("com.mysql.jdbc.Driver");
      // 2.获取连接
      String url = "jdbc:mysql://localhost:3306/boot_crm";
      String user = "root";
      String password = "666666";
      connection = DriverManager.getConnection(url, user, password);
      // 3.构造一个statement对象来执行sql语句：主要有Statement，PreparedStatement，CallableStatement三种实例来实现
      // 三种实现方法分别为：Statement stmt = con.createStatement() ;
      //          PreparedStatement pstmt = conn.prepareStatement(sql) ;
      //
      //          CallableStatement cstmt = conn.prepareCall("{CALL demoSp(? , ?)}") ;

      statement = connection.createStatement();

      // 执行SQL语句
      // 新增
      //      String sqlString ="insert into sys_user(user_code,user_name,user_password) value
      // ('m004','kyrie_irving',123456)";

      // 修改
      //        String sqlString = "update sys_user set user_password = '123' where user_id = 3";
      // 删除
      // 取消自动事务回滚
      connection.setAutoCommit(false);
      String sqlString = "delete from sys_user where user_id = 4";

      n = statement.executeUpdate(sqlString);
      connection.commit();
    } catch (ClassNotFoundException | SQLException e) {
      try {
        // 回滚事务
        connection.rollback();
      } catch (SQLException ex) {
        ex.printStackTrace();
      }
      e.printStackTrace();
    } finally {
      // 关闭资源
      try {
        if (statement != null) {
          statement.close();
        }

      } catch (SQLException e) {
        e.printStackTrace();
      }
      try {
        if (connection != null) {
          connection.close();
        }
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }

    if (n > 0) {
      System.out.println("新增成功");
    } else {
      System.out.println("新增失败");
    }
  }
}
